import { createRouter, createWebHistory } from "vue-router";
import { getToken } from "@/utils/token";
import routes from "./userouters"
// import userRoutersStore from "../store/userouter";

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes
})

// 全局前置导航守卫，用来给页面鉴权
router.beforeEach(async (to, from, next) => {
    const token = getToken("token");
    // const routerData = userRoutersStore().routesTable;
    // router.addRoute(
    //     {
    //         path: routerData.path,
    //         name: routerData.name,
    //         component: () => import(`@/views/user/${routerData.component}.vue`),
    //         meta: routerData.meta
    //     }
    // )

    if (token) {
        if (to.path === '/login') {
            next('/');
        } else {
            next();
        }
    } else {
        if (to.meta.requiresAuth) {
            if (to.path !== '/login') {
                next('/login')
            } else {
                next();
            }
        } else {
            next();
        }
    }
})

// 全局后置导航守卫，用来监视页面跳转
router.afterEach(async (to, from) => {
    console.log(`从 ${from.fullPath} 到 ${to.fullPath} 页面`)
})

export default router;